//
//  ViewModel.swift
//  JiaoZiTaxi
//
//  Created by Hu Gang on 2022/10/30.
//

import Foundation
import MapKit
import Localize_Swift

extension EnumLanguage {
    func toString() -> String {
        switch self {
        case .Chinese:
            return "chinese"
        case .English:
            return "english"
        case .Laos:
            return "lao"
        }
    }
}

enum EnumLanguage : String {
    case Chinese = "zh-Hans"
    case English = "en"
    case Laos = "lo"
}

class ViewModel : ObservableObject {
    static let shared = ViewModel()
    
    @Published var language : EnumLanguage = .Chinese {
        willSet {
            UserDefaults.standard.setValue(newValue.rawValue, forKey: "locale")
            Localize.setCurrentLanguage(newValue.rawValue)
            self.currentCityName = getCurrentCityName()
        }
    }
    
    @Published var passenger = Passenger()
    @Published var order = CarOrder.shared
    @Published var car : CarInfo?
    @Published var cars : [CarInfo]?
    @Published var nearCarCount : Int = 1
    
    @Published var selectAddressName: String = ""   // 选中后的地址名称
    @Published var deviceToken : String = ""
    
    @Published var cities: [DataCity] = []
    @Published var currentCity: String = "" {
        willSet {
            UserDefaults.standard.setValue(newValue, forKey: "CurrentCityCode")
            self.currentCityName = getCurrentCityName()
        }
    }
    @Published var currentCityName: String = "万象"
    @Published var shortMessages: [DataShortMessage] = []
    @Published var pathCoordinates: [CLLocationCoordinate2D] = []
    @Published var debugMode = false
    @Published var isShowSuccessView = false
    
    var releaseMode : Bool = true
    @Published var appVersion : String = "1.0.0"
    
    @Published var needReturnToUserLocation = true
    
    var inChat = false
    
    var lastLocation : CLLocationCoordinate2D {
        willSet {
            //print("lastLocation changed:\(newValue)")
        }
    }
    
    @Published var startLocation : CLLocationCoordinate2D {
        willSet {
            print("[Map] startLocation changed:\(newValue)")
        }
    }
    
    @Published var endLocation : CLLocationCoordinate2D {
        willSet {
            print("[Map] endLocation changed:\(newValue)")
        }
    }
    
    private init() {
        //First get the nsObject by defining as an optional anyObject
        let nsObject: AnyObject? = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as AnyObject
        
        //Then just cast the object as a String, but be careful, you may want to double check for nil
        appVersion = nsObject as! String
        
        // locale
        let locale = UserDefaults.standard.string(forKey: "locale")
        if let saveLaunage = locale {
            language = EnumLanguage(rawValue: saveLaunage)!
        } else {
            language = .Chinese
        }
        
        if let cityCode = UserDefaults.standard.string(forKey: "CurrentCityCode") {
            currentCity = cityCode
        } else {
            currentCity = "1"
        }
        
        // 读取乘客信息
        let data = UserDefaults.standard.string(forKey: "Passenger")
        if let d = data {
            print("本地读取乘客信息成功")
            let coder = JSONDecoder()
            if let p = try? coder.decode(Passenger.self,from:Data(d.utf8)) {
                passenger = p
            }
        }else{
            print("本地读取乘客信息失败")
        }
        
        //lastLocation = LocationManager.shared.lastLocation!.coordinate
        
        if let loc = LocationManager.shared.lastLocation {
            lastLocation = loc.coordinate
            startLocation = lastLocation
            endLocation = lastLocation
        } else {
            let lat = UserDefaults.standard.double(forKey: "lastLocation.lat")
            let lon = UserDefaults.standard.double(forKey: "lastLocation.lon")
            lastLocation = CLLocationCoordinate2D(latitude:lat,longitude:lon)
            startLocation = lastLocation
            endLocation = lastLocation
        }
        
        print("vm inited: \(lastLocation)")
        
        currentCityName = self.getCurrentCityName()
        
        //let dmode = UserDefaults.standard.bool(forKey: "debugMode")
        //debugMode = dmode
    }
    
    func saveLastLocation() {
        let lat = lastLocation.latitude
        let lon = lastLocation.longitude
        UserDefaults.standard.setValue(lat, forKey: "lastLocation.lat")
        UserDefaults.standard.setValue(lon, forKey: "lastLocation.lon")
        print("写入本地的坐标 : vm lastlocation saved. lat:\(lat)  lon:\(lon)")
    }
    
    func getCities() -> [DataDisplayCity] {
        var cities = [DataDisplayCity]()
        
        switch language {
        case .Chinese:
            self.cities.forEach { c in
                cities.append(DataDisplayCity(code: c.code, name: c.name))
            }
        case .English:
            self.cities.forEach { c in
                cities.append(DataDisplayCity(code: c.code, name: c.nameEn))
            }
        case .Laos:
            self.cities.forEach { c in
                cities.append(DataDisplayCity(code: c.code, name: c.nameLao))
            }
        }
        
        return cities
    }
    
    func getShortMessages() -> [DataShortMessage] {
        var messages = [DataShortMessage]()
        // 只取用户的短语
        let customerShortMessage: [DataShortMessage] = self.shortMessages.filter { x in
            x.customer == "1"
        }
        switch self.language {
        case .Chinese:
            messages = customerShortMessage.filter({ x in
                x.language == "chinese"
            })
        case .English:
            messages = customerShortMessage.filter({ x in
                x.language == "english"
            })
        case .Laos:
            messages = customerShortMessage.filter({ x in
                x.language == "lao"
            })
        }
        
        return messages
    }
    
    func getCurrentCityName() -> String {
        var city = "万象"
        
        if let current = self.cities.first(where: { c in
            c.code == self.currentCity
        }) {
            switch self.language {
            case .Chinese:
                city = current.name
            case .English:
                city = current.nameEn
            case .Laos:
                city = current.nameLao
            }
        }
        
        return city
    }
    
    func getShortMessageContent(code: String) -> String {
        var lang = "chinese"
        var content = ""
        
        switch self.language {
        case .Chinese:
            lang = "chinese"
        case .English:
            lang = "english"
        case .Laos:
            lang = "lao"
        }
        
        
        if let spec = self.shortMessages.first(where: { c in
            c.code == code && c.language == lang
        }) {
            content = spec.content
        }
        
        return content
    }
    
    func initCurrentCity() {
        if let code = UserDefaults.standard.string(forKey: "CurrentCityCode") {
            self.currentCity = code
            self.currentCityName = self.getCurrentCityName()
        }
    }
}
